<?php

namespace frontend\modules\touch\controllers;

use yii\web\Controller;
use common\components\Tools;
use common\components\MobileDetect;
use backend\modules\home\models\Booklist;
use backend\modules\home\models\Banner;
use backend\modules\home\models\Collection;
use backend\modules\home\models\Taglist;
use backend\modules\home\models\Vip;
use common\models\FrontLoginForm;
use frontend\models\SignupForm;
use yii\data\Pagination;
use yii\myhelper\Response;
use Yii;

/**
 * Default controller for the `touch` module
 */
class DefaultController extends Controller
{
    /**
     * Renders the index view for the module
     * @return string
     */
    public $enableCsrfValidation = false;
    public $layout = 'main';

    public function actionLogin()
    {
        if (!Yii::$app->user->isGuest) {
            return $this->redirect('/touch/default/index');
        }

        $model = new FrontLoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->redirect('/touch/default/index');
        } else {
            $model->password = '';

            return $this->render('login', [
                'model' => $model,
            ]);
        }
    }

    public function actionSignup()
    {
        if (!Yii::$app->user->isGuest) {
            return $this->redirect('/touch/default/index');
        }

        $model = new SignupForm();
        if ($model->load(Yii::$app->request->post())) {
            if ($user = $model->signup()) {
                if (Yii::$app->getUser()->login($user)) {
                    return $this->redirect('/touch/default/index');
                }
            }
        }

        return $this->render('signup', [
            'model' => $model,
        ]);
    }

    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->redirect('/touch/default/login');
    }

    public function actionHome(){
        $query = Booklist::find()->where(['status' => 1,'parent_id' => 0]);
        $query->orderBy([
            'create_at' => SORT_DESC,
        ]);
        $new_list = $query->limit(6)->asArray()->all();
        return $this->render('home',[
            'new_list' => $new_list,
        ]);
    }

    public function actionMoreList(){

        $current_page = Yii::$app->request->get('page');
        if(!$current_page){
            $current_page = 1;
        }

        $query = Booklist::find()->where(['status' => 1,'parent_id' => 0]);
        $type = Yii::$app->request->get('type');
        if($type == 'recommend'){
            $title = '强烈推荐';
            $query->orderBy([
                'click_num' => SORT_DESC,
                'create_at' => SORT_DESC,
            ]);

        }elseif($type == 'over'){
            $title = '经典完结';
            $query->andWhere(['is_over' => 1]);
            $query->orderBy([
                'update_at' => SORT_DESC,
            ]);
        }elseif($type == 'free'){
            $title = '免费漫画';
            $query->andWhere(['is_free' => 0]);
            $query->orderBy([
                'update_at' => SORT_DESC,
            ]);
        }else{
            $title = '新品发布';
            $query->orderBy([
                'create_at' => SORT_DESC,
            ]);
        }

        $total_count = $query->count();
        $total_page = ceil($total_count/3);
        if($current_page > $total_page){
            Response::show('201','我是有底线的',[]);
        }
        $pages = new Pagination(['totalCount' =>$total_count, 'pageSize' => '3']);
        $list = $query->offset($pages->offset)->limit($pages->limit)->asArray()->all();

        if($current_page != 1){
            Response::show(200,'success',['list' => $list,'page' => $current_page]);
        }else{
            return $this->render('more-list',[
                'title' => $title,
                'list' => $list,
                'type' => $type,
            ]);
        }

    }

    public function actionIndex()
    {
        $detect = new MobileDetect();
        if(!$detect->isMobile()){
            return $this->redirect('/home/default/index');exit;
        }
        $query = Booklist::find()->where(['status' => 1,'parent_id' => 0]);

        $new_list = $query->orderBy([
            'create_at' => SORT_DESC,
            ])
            ->limit(6)
            ->asArray()
            ->all();
        $recommend_list = Booklist::find()->where(['status' => 1,'parent_id' => 0])->orderBy([
            'zan_num' => SORT_DESC,
            'click_num' => SORT_DESC,
            ])
            ->limit(6)
            ->asArray()
            ->all();
        $over_list = Booklist::find()->where(['status' => 1,'parent_id' => 0,'is_over' => 1])
            ->orderBy([
                'update_at' => SORT_DESC,
            ])
            ->limit(6)
            ->asArray()
            ->all();
        $free_list = Booklist::find()->where(['status' => 1,'parent_id' => 0,'is_free' => 0])
            ->orderBy([
                'create_at' => SORT_DESC,
            ])
            ->limit(6)
            ->asArray()
            ->all();



        $bannerlist = Banner::find()
            ->where(['cid' => 2])
            ->orderBy([
                'sort' => SORT_DESC,
                'id' => SORT_ASC,
            ])
            ->asArray()
            ->all();

        // 连载中
        $lianzai_list = Booklist::find()->where(['status' => 1,'parent_id' => 0,'is_over' => 0])
            ->orderBy([
                'create_at' => SORT_DESC,
            ])
            ->limit(9)
            ->all();

        return $this->render('index',[
            'new_list' => $new_list,
            'recommend_list' => $recommend_list,
            'over_list' => $over_list,
            'free_list' => $free_list,
            'bannerlist' => $bannerlist,
            'lianzai_list' => $lianzai_list,
        ]);
    }

    public function actionUcenter(){

        if (Yii::$app->user->isGuest) {
            return $this->redirect('/touch/default/login');
        }

        $id = Yii::$app->user->identity->id;

        $vip_model = Vip::findOne(['uid' => $id]);
        $vip = false;

        if($vip_model){

            if($vip_model->expire_time <= time()){
                $vip_model = false;
            }else{
                $exp = $vip_model->expire_time - time();
                if($exp > 2*365*24*3600){
                    $vip = '终生会员';
                }
            }
        }else{
            $vip_model = false;
        }

        return $this->render('ucenter',[
            'ucenter' => Yii::$app->user->identity,
            'vip_model' => $vip_model,
            'vip' => $vip,
        ]);
    }

    public function actionFeedback(){
        return $this->redirect('/touch/error?msgid=210');exit;
    }

    public function actionCate(){
        if($cate = Yii::$app->request->get('cate')){
            $cate = intval($cate);
        }else{
            $cate = 0;
        }
        if($tag = Yii::$app->request->get('tag')){
            $tag = intval($tag);
        }else{
            $tag = 0;
        }

        $taglist = Taglist::find()->asArray()->all();
        return $this->render('cate',[
            'taglist' => $taglist,
            'tag' => $tag,
            'cate' => $cate,
        ]);
    }

    public function actionList(){
        $current_page = Yii::$app->request->get('page');
        if(!$current_page){
            $current_page = 1;
        }

        $query = Booklist::find()->where(['status' => 1,'parent_id' => 0]);

        if($cate = Yii::$app->request->get('cate')){
            if($cate == 1){
                $query->andWhere(['cid' => 1]);
            }
            if($cate == 2){
                $query->andWhere(['cid' => 2]);
            }
        }
        if($tag = Yii::$app->request->get('tag')){
            $tag = intval($tag);
            $query->andWhere(['like', 'mark', $tag]);
        }
        $query->orderBy([
//            'sort' => SORT_DESC,
            'create_at' => SORT_DESC,
        ]);

        $total_count = $query->count();
        $total_page = ceil($total_count/9);
        if($current_page > $total_page){
            Response::show('201','我是有底线的',[]);
        }

        $pages = new Pagination(['totalCount' =>$total_count, 'pageSize' => '9']);
        $list = $query->offset($pages->offset)->limit($pages->limit)->asArray()->all();


        Response::show(200,'success',['list' => $list,'page' => $current_page]);

    }

    public function actionBookItem($id){
        $this->layout = false;
        $detect = new MobileDetect();
        if(!$detect->isMobile()){
            return $this->redirect('/home/default/index');exit;
        }
        $model = $this->check($id);
        if(!$model){
            return $this->redirect('/touch/error?msgid=201');exit;
        }
        // 增加阅读量
        $model->click_num = $model->click_num + 1;
        $model->save();

        $list = array();
        if($model->type == 2){
            $list = Booklist::find()
                ->where([
                    'status' => 1,
                    'parent_id' => $model->id,
                ])
                ->select('number,front_title')
                ->orderBy([
                    'sort' => SORT_DESC,
                    'create_at' => SORT_ASC,
                ])
                ->asArray()
                ->all();
        }

        $like = $this->getRandomlist();

        return $this->render('book-item',[
            'model' => $model,
            'list' => $list,
            'like' => $like,
        ]);
    }

    public function actionCatalog(){
        if(!$number = Yii::$app->request->get('idpro')){
            $number = Yii::$app->request->get('id');
            $model = $this->check($number);
        }else{
            $model = $this->check($number,'id');
        }
        if(!$model){
            return $this->redirect('/touch/error?msgid=201');exit;
        }
        $list = Booklist::find()
            ->where([
                'status' => 1,
                'parent_id' => $model->id,
            ])
            ->select('number,front_title,is_free')
            ->orderBy([
                'sort' => SORT_DESC,
                'create_at' => SORT_ASC,
            ])
            ->asArray()
            ->all();

        return $this->render('catalog',[
            'list' => $list,
            'model' => $model,
        ]);

    }

    public function actionFavorite(){
        if (Yii::$app->user->isGuest) {
            return $this->redirect('/touch/default/login');
        }

        $query = Collection::find()->where(['uid' => Yii::$app->user->identity->id]);
        $query->with('bookInfo');
        $query->orderBy('create_at desc');
        $query->limit(20);
        $list = $query->asArray()->all();

        return $this->render('favorite',[
            'list' => $list
        ]);
    }

    public function actionCollection()
    {
        if (Yii::$app->user->isGuest) {
            Response::show(202,'未登录',[]);
        }
        if($number = Yii::$app->request->post('code')){

            $select = Booklist::find()
                ->where([
                    'status' => 1,
                    'number' => $number,
                ])->one();
            if(!$select){
                Response::show(201,'参数错误',[]);
            }
            $model = new Collection();
            $select_collection = $model::find()
                ->where([
                    'uid' => Yii::$app->user->identity->id,
                    'book_code' => $number,
                ])->one();
            if($select_collection){
                Response::show(201,'已收藏',[]);
            }
            $model->uid = Yii::$app->user->identity->id;
            $model->book_code = $number;
            $model->create_at = time();
            if(!$model->save()){

                echo "<pre>";
                var_dump($model->errors);exit;
            }
            $select->zan_num = $select->zan_num + 1;
            $select->save();
            Response::show(200,'收藏成功',[]);
        }else{
            Response::show(201,'参数错误',[]);
        }

    }

    public function actionRankingList(){
        $query = Booklist::find()->where(['status' => 1,'parent_id' => 0]);
        $tab = Yii::$app->request->get('tab');
        if($tab == 'like'){
            $tab = 'like';
            $query->orderBy([
                'zan_num' => SORT_DESC,
                'click_num' => SORT_DESC,
            ]);
        }else{
            $tab = 'num';
            $query->orderBy([
                'click_num' => SORT_DESC,
                'zan_num' => SORT_DESC,
            ]);
        }
        $query->limit(20);
        $list = $query->asArray()->all();

        return $this->render('ranking-list',[
            'tab' => $tab,
            'list' => $list,
        ]);
    }

    public function actionView($id){

        $this->layout = false;

        $detect = new MobileDetect();
        if(!$detect->isMobile()){
            return $this->redirect('/touch/error?msgid=202');exit;
        }
        $model = $this->check($id);
        if(!$model){
            return $this->redirect('/touch/error?msgid=201');exit;
        }

        // 判断本章是否付费
        if($model->is_free == 1){
            // 判断是否登录
            if (Yii::$app->user->isGuest) {
                return $this->redirect('/touch/default/login');
            }
            // 判读是否是会员 时间到期没有
            $vip_model = Vip::findOne(['uid' => Yii::$app->user->identity->id]);
            if(!$vip_model){
                return $this->redirect('/touch/default/rechange');
            }else{
                // 时间到期没有
                if($vip_model->expire_time <= time()){
                    return $this->redirect('/touch/default/rechange');
                }
            }
        }


        $parent_model = $this->check($model->parent_id,'id');
        if(!$parent_model){
            return $this->redirect('/touch/error?msgid=201');exit;
        }

        // 上一章
        $pre_model = Booklist::find()
            ->select('max(id),number')
            ->where([
                'status' => 1,
                'parent_id' => $model->parent_id,
            ])
            ->andWhere(['<','id',$model->id])
            ->asArray()
            ->one();
        // 下一章
        $next_model = Booklist::find()
            ->select('min(id),number')
            ->where([
                'status' => 1,
                'parent_id' => $model->parent_id,
            ])
            ->andWhere(['>','id',$model->id])
            ->asArray()
            ->one();

        return $this->render('view',[
            'model' => $model,
            'idpro' => $model->parent_id,
            'title' => $parent_model->front_title,
            'parent_model' => $parent_model,
            'next_model' => $next_model,
            'pre_model' => $pre_model,
        ]);
    }

    public function actionSearch(){

        if($search = Yii::$app->request->get('search')){
            $query = Booklist::find()->where(['status' => 1,'parent_id' => 0]);
            $query->andWhere(['like', 'front_title', $search]);
            $query->orderBy([
                'sort' => SORT_DESC,
                'update_at' => SORT_DESC,
            ]);
            $list = $query->asArray()->all();
            $searchlist = false;
        }else{
            $list = false;
            $search = '';
            $query = Booklist::find()->select('front_title,number')->where(['status' => 1,'parent_id' => 0]);
            $query->orderBy([
                'zan_num' => SORT_DESC,
                'click_num' => SORT_DESC,
            ]);
            $searchlist = $query->limit(6)->asArray()->all();
        }

        return $this->render('search',[
            'list' => $list,
            'search' => $search,
            'searchlist' => $searchlist
        ]);
    }

    public function actionRechange(){
        $this->layout = false;
        return $this->render('rechange',[

        ]);
    }

    public function actionDownload(){
        $this->layout = false;
        return $this->render('download',[

        ]);
    }

    public function actionOrder(){

        Response::show('200','我是有底线的',[]);
    }

    public function check($id,$colume = 'number'){
        if($colume == 'id'){
            $where = [
                'status' => 1,
                'id' => $id,
            ];
        }else{
            $where = [
                'status' => 1,
                'number' => $id,
            ];
        }
        $model = Booklist::find()
            ->where($where)->one();
        return $model;

    }

    public function getRandomlist(){
        $idlist = Booklist::find()
            ->where(['status' => 1, 'parent_id' => 0])
            ->select('id')
            ->asArray()
            ->all();
        foreach($idlist as $v){
            $ids[] = $v['id'];
        }
        $rand_key = array_rand($ids,6);
        foreach($rand_key as $v){
            $numbers[] = $ids[$v];
        }
        $list = Booklist::find()
            ->select('id,number,front_title,thumb_img')
            ->where(['status' => 1,'parent_id' => 0])
            ->andWhere(['in','id',$numbers])
            ->orderBy([
                'sort' => SORT_DESC,
                'click_num' => SORT_DESC,
                'update_at' => SORT_DESC,
            ])
            ->asArray()
            ->all();
        return $list;

    }
}
